// package: learn-go
// filename: WebSocket
// author: diogoxiang@gmail.com
// time: 2024/1/9 11:23

package main

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtimer"
	"time"
)

var ctx = gctx.New()

func addGtimer(ws *ghttp.WebSocket) {
	var (
		//ctx      = gctx.New()
		interval = time.Second
	)

	gtimer.AddSingleton(ctx, interval, func(ctx context.Context) {
		glog.Print(ctx, "doing")
		time.Sleep(4 * time.Second)
		//ws.WriteMessage(ghttp.WsMsgText, []byte(`{"code":200,"msg":"心跳消息"}`))
		ws.WriteMessage(ghttp.WsMsgText, []byte(`{"msg":"4444","messageStatus":0,"code":0,"createTime":"2024-02-21 16:56:18","avatarSrc":"https://foruda.gitee.com/avatar/1676896278094929305/16956_diogoxiang_1578915127.png","msgId":"237f4f7c4371465fb79ccf45fb51d022","onlineUsers":2,"buddyId":"237f4f7c4371465fb79ccf45fb51d022","userID":"67f632b1698f45d38d76f55e86577d43","username":"diogoxiang"}`))
	})
}

func main() {
	s := g.Server()
	s.BindHandler("/ws", func(r *ghttp.Request) {
		ws, err := r.WebSocket()
		if err != nil {
			glog.Error(ctx, err)
			r.Exit()
		}
		//addGtimer(ws)

		for {
			msgType, msg, err := ws.ReadMessage()
			if err != nil {
				return
			}

			switch msgType {
			case ghttp.WsMsgText:
				glog.Info(ctx, "msg text recv: ", string(msg))
			case ghttp.WsMsgBinary:
				glog.Info(ctx, "msg Binary recv: ", string(msg))
			case ghttp.WsMsgClose:
				glog.Info(ctx, "recv: close")
				return
			case ghttp.WsMsgPing:
				glog.Info(ctx, "recv: ping")
				if err = ws.WriteMessage(msgType, msg); err != nil {
					return
				}
			}

			if err = ws.WriteMessage(msgType, msg); err != nil {
				return
			}

		}

	})
	s.SetServerRoot(gfile.MainPkgPath())
	s.SetPort(8199)
	s.Run()
}
